<?php

namespace Kateba\SiteBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Validator\Constraints\Collection;
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Validator\Constraints\Email;
use Kateba\SiteBundle\Entity\UserService;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

require_once __DIR__ . '/../Resources/paypal/Paypal.php';

class SiteController extends Controller {

    /**
     * privacy page action
     * @author ahmed
     */
    public function privacyAction($_locale) {
        if ($_locale === 'ar') {
            $privacyPath = __DIR__ . '/../../../../web/site-pages/privacy-ar.html';
        } else {
            $privacyPath = __DIR__ . '/../../../../web/site-pages/privacy-en.html';
        }
        $content = file_get_contents($privacyPath);
        return $this->render('KatebaSiteBundle:Site:privacy.html.twig', array('content' => $content));
    }

    /**
     * terms page action
     * @author ahmed
     */
    public function termsAction($_locale) {
        if ($_locale === 'ar') {
            $termsPath = __DIR__ . '/../../../../web/site-pages/terms-ar.html';
        } else {
            $termsPath = __DIR__ . '/../../../../web/site-pages/terms-en.html';
        }
        $content = file_get_contents($termsPath);
        return $this->render('KatebaSiteBundle:Site:terms.html.twig', array('content' => $content));
    }

    /**
     * career page action
     * @author ahmed
     */
    public function careerAction($_locale) {
        if ($_locale === 'ar') {
            $careerPath = __DIR__ . '/../../../../web/site-pages/career-ar.html';
        } else {
            $careerPath = __DIR__ . '/../../../../web/site-pages/career-en.html';
        }
        $content = file_get_contents($careerPath);
        return $this->render('KatebaSiteBundle:Site:career.html.twig', array('content' => $content));
    }

    /**
     * show user services details
     * @author ahmed
     */
    public function myServicesAction(Request $request, $_locale) {
        if (FALSE === $this->get('security.context')->isGranted('ROLE_USER')) {
            //get the session
            $session = $this->get('session');
            //clear the previous flashes
            $session->getFlashBag()->clear();
            if (TRUE === $this->get('security.context')->isGranted('ROLE_NOTACTIVE')) {
                //add success flash
                $session->getFlashBag()->set('activationNeed', true);
                return $this->redirect($this->generateUrl('login'));
            } else {
                //add success flash
                $session->getFlashBag()->set('loginNeed', true);
                return $this->redirect($this->generateUrl('login'));
            }
        }
        //get the logedin user
        $user = $this->get('security.context')->getToken()->getUser();
        $em = $this->getDoctrine()->getEntityManager();
        $userServiceRepo = $em->getRepository('KatebaSiteBundle:UserService');

        $itemsPerPage = 15;
        $page = $request->get('page', 1);

        $data = $userServiceRepo->getUserServices($user->getId(), $page, $itemsPerPage);
        $entities = $data['entities'];
        $count = $data['count'];
        //calculate the last page number
        $lastPageNumber = (int) ($count / $itemsPerPage);
        if (($count % $itemsPerPage) > 0) {
            $lastPageNumber++;
        }

        return $this->render('KatebaSiteBundle:Site:myServices.html.twig', array(
                    'services' => $entities,
                    'page' => $page,
                    'locale' => $_locale,
                    'lastPageNumber' => $lastPageNumber
        ));
    }

    /**
     * add service to user and send email to admin for cash
     * @author ahmed
     * @param string $_locale
     * @param int $serviceId
     * @return type
     */
    public function cashPaymentAction($_locale, $serviceId, $isRush) {
        if (FALSE === $this->get('security.context')->isGranted('ROLE_USER')) {
            //get the session
            $session = $this->get('session');
            //clear the previous flashes
            $session->getFlashBag()->clear();
            //add success flash
            $session->getFlashBag()->set('loginNeed', true);
            return $this->redirect($this->generateUrl('login'));
        }

        $em = $this->getDoctrine()->getEntityManager();
        $serviceRepo = $em->getRepository('KatebaSiteBundle:Service');
        $userServiceRepo = $em->getRepository('KatebaSiteBundle:UserService');

        $service = $serviceRepo->find($serviceId);
        if (!$service) {
            throw $this->createNotFoundException('Unable to find this service.');
        }

        //get the logedin user
        $user = $this->get('security.context')->getToken()->getUser();

        //check for reload
        $userServiceFlag = $userServiceRepo->findOneBy(array('service' => $serviceId, 'user' => $user->getId(), 'active' => 1));

        if (!$userServiceFlag && $user->getCountry() == 'Egypt') {
            //create new user service
            $newUserService = new UserService();
            $newUserService->setUser($user);
            $newUserService->setService($service);
            $newUserService->setIsPaypal(FALSE);
            if ($isRush)
                $newUserService->setIsRush(TRUE);

            $em->persist($newUserService);
            $em->flush();

            //send email to the admin
            $subject = 'Educino - New Service';
            $message = $this->renderView('KatebaSiteBundle:Site:cashPaymentEmail.html.twig', array(
                'user' => $user,
                'service' => $service,
                'userService' => $newUserService
            ));
            $headers = 'From: Educino <' . $this->container->getParameter('admin_notifications_email') . '>' . "\r\n";
            $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
            mail($this->container->getParameter('admin_notifications_email'), $subject, $message, $headers);

//            $message = \Swift_Message::newInstance()
//                    ->setSubject('Educino - New Service')
//                    ->setFrom($this->container->getParameter('admin_notifications_email'))
//                    ->setTo($this->container->getParameter('admin_notifications_email'))
//                    ->setBody($this->renderView('KatebaSiteBundle:Site:cashPaymentEmail.html.twig', array(
//                        'user' => $user,
//                        'service' => $service,
//                        'userService' => $newUserService
//                    )))
//            ;
//            //send the mail
//            $this->get('mailer')->send($message);

            $result = TRUE;
        } else {
            $result = FALSE;
        }

        return $this->render('KatebaSiteBundle:Site:cashPayment.html.twig', array(
                    'result' => $result
        ));
    }

    /**
     * this function will used to insert payment data after payment success
     * @author ahmed
     */
    public function paymentSuccessAction() {
        if (FALSE === $this->get('security.context')->isGranted('ROLE_USER')) {
            //get the session
            $session = $this->get('session');
            //clear the previous flashes
            $session->getFlashBag()->clear();
            //add success flash
            $session->getFlashBag()->set('loginNeed', true);
            return $this->redirect($this->generateUrl('login'));
        }

        //get the logedin user
        $user = $this->get('security.context')->getToken()->getUser();

        $myPaypal = new \Paypal();
        $myPaypal->validateIpn();
        if (isset($_POST['payment_status']) && $_POST['payment_status'] == 'Completed') {
            $em = $this->getDoctrine()->getEntityManager();
            $serviceRepo = $em->getRepository('KatebaSiteBundle:Service');
            //get the service
            $service = $serviceRepo->find($_POST['item_number']);

            //create new user service
            $newUserService = new UserService();
            $newUserService->setUser($user);
            $newUserService->setService($service);
            $newUserService->setPayerEmail($_POST['payer_email']);
            $newUserService->setTransactionId($_POST['txn_id']);
            if ($_POST['custom'] == 1)
                $newUserService->setIsRush(TRUE);

            $em->persist($newUserService);
            $em->flush();

            //send email to the admin
            $subject = 'Educino - New Service';
            $message = $this->renderView('KatebaSiteBundle:Site:paymentSuccessEmail.html.twig', array(
                'user' => $user,
                'service' => $service,
                'userService' => $newUserService
            ));
            $headers = 'From: Educino <' . $this->container->getParameter('admin_notifications_email') . '>' . "\r\n";
            $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
            mail($this->container->getParameter('admin_notifications_email'), $subject, $message, $headers);

//            $message = \Swift_Message::newInstance()
//                    ->setSubject('Educino - New Service')
//                    ->setFrom($this->container->getParameter('admin_notifications_email'))
//                    ->setTo($this->container->getParameter('admin_notifications_email'))
//                    ->setBody($this->renderView('KatebaSiteBundle:Site:paymentSuccessEmail.html.twig', array(
//                        'user' => $user,
//                        'service' => $service,
//                        'userService' => $newUserService
//                    )))
//            ;
//            //send the mail
//            $this->get('mailer')->send($message);

            return $this->render('KatebaSiteBundle:Site:paymentSuccess.html.twig', array(
                        'result' => TRUE
            ));
        }

        return $this->render('KatebaSiteBundle:Site:paymentSuccess.html.twig', array(
                    'result' => FALSE
        ));
    }

    /**
     * this function used to to pay a srvice
     * @author ahmed
     * @param integer $serviceId
     */
    public function confirmPaymentAction($_locale, $serviceId, $isRush) {
        if (FALSE === $this->get('security.context')->isGranted('ROLE_USER')) {
            //get the session
            $session = $this->get('session');
            //set the url in session
            $session->set('redirectUrl', $this->generateUrl('service_pay', array('serviceId' => $serviceId, '_locale' => $_locale, 'isRush' => $isRush)));
            //clear the previous flashes
            $session->getFlashBag()->clear();
            //add success flash
            $session->getFlashBag()->set('loginNeed', true);
            return $this->redirect($this->generateUrl('login'));
        }

        $em = $this->getDoctrine()->getEntityManager();
        $serviceRepo = $em->getRepository('KatebaSiteBundle:Service');

        $service = $serviceRepo->find($serviceId);
        if (!$service) {
            throw $this->createNotFoundException('Unable to find this service.');
        }

        $myPaypal = new \Paypal();
        $myPaypal->addField('rm', 2);
        $myPaypal->addField('business', $this->container->getParameter('paypal_email'));
        $myPaypal->addField('currency_code', 'USD');
        $myPaypal->addField('return', $this->generateUrl('payment_success', array(), TRUE));
        $myPaypal->addField('notify_url', $this->generateUrl('payment_success', array(), TRUE));
        $myPaypal->addField('cancel_return', $this->generateUrl('services', array(), TRUE));
        $myPaypal->addField('item_name', $service->getName($_locale));
        if ($isRush)
            $myPaypal->addField('amount', $service->getRushPrice());
        else
            $myPaypal->addField('amount', $service->getPrice());
        $myPaypal->addField('item_number', $service->getId());
        $myPaypal->addField('custom', $isRush);

        return $this->render('KatebaSiteBundle:Site:confirmPayment.html.twig', array(
                    'html' => $myPaypal->submitPayment(),
                    'locale' => $_locale,
                    'isRush' => $isRush,
                    'serviceId' => $serviceId
        ));
    }

    /**
     * list category services
     * @author ahmed
     * @param int $categoryId
     */
    public function categoryServicesAction($_locale, $categoryId, $page) {
        $em = $this->getDoctrine()->getEntityManager();
        $categoryRepo = $em->getRepository('KatebaSiteBundle:Category');
        $serviceRepo = $em->getRepository('KatebaSiteBundle:Service');

        $category = $categoryRepo->find($categoryId);
        if (!$category) {
            return new Response('failed');
        }

        $itemsPerPage = 10;
        $data = $serviceRepo->getCategoryServices($page, $itemsPerPage, $categoryId);
        $entities = $data['entities'];
        $count = $data['count'];
        //calculate the last page number
        $lastPageNumber = (int) ($count / $itemsPerPage);
        if (($count % $itemsPerPage) > 0) {
            $lastPageNumber++;
        }

        return $this->render('KatebaSiteBundle:Site:categoryServices.html.twig', array(
                    'category' => $category,
                    'services' => $entities,
                    'page' => $page,
                    'lastPageNumber' => $lastPageNumber,
                    'locale' => $_locale
        ));
    }

    /**
     * this function used to show site services
     * @author ahmed
     */
    public function servicesAction($_locale) {
        $em = $this->getDoctrine()->getEntityManager();
        $categoryRepo = $em->getRepository('KatebaSiteBundle:Category');
        //get all categories
        $categories = $categoryRepo->findAll();


        return $this->render('KatebaSiteBundle:Site:services.html.twig', array(
                    'categories' => $categories,
                    'locale' => $_locale
        ));
    }

    /**
     * home page
     * @author Mahmoud
     * @param string $locale
     */
    public function homeAction($_locale) {
        $response = new Response();
        $em = $this->getDoctrine()->getEntityManager();
        $slides = $em->getRepository('KatebaSiteBundle:Slider')->findBy(array(), array('priority' => 'DESC'));
        $posts = $em->getRepository('KatebaSiteBundle:Post')->findBy(array('active' => 1), array('createdAt' => 'DESC'), 3);
        $questions = $em->getRepository('KatebaSiteBundle:Question')->findBy(array('approved' => 1), array('createdAt' => 'DESC'), 4);
        $response = $this->render('KatebaSiteBundle:Site:home.html.twig', array(
            'locale' => $_locale,
            'slides' => $slides,
            'questions' => $questions,
            'posts' => $posts
        ));

//        $response->setETag(md5($response->getContent()));
//        $response->setPublic();
//        $response->isNotModified($this->getRequest());
        return $response;
    }

    /**
     * @author Mahmoud
     */
    public function contactUsAction() {
        $contact = array();
        if (true === $this->get('security.context')->isGranted('ROLE_NOTACTIVE')) {
            $user = $this->get('security.context')->getToken()->getUser();
            $contact['name'] = $user->__toString();
            $contact['email'] = $user->getEmail();
        }
        $collectionConstraint = new Collection(array(
            'name' => array(
                new NotBlank()
            ),
            'email' => array(
                new NotBlank(),
                new Email()
            ),
            'subject' => array(
                new NotBlank()
            ),
            'message' => array(
                new NotBlank()
            )
        ));
        $form = $this->createFormBuilder($contact, array('constraints' => $collectionConstraint))
                ->add('name')
                ->add('subject')
                ->add('email', 'email')
                ->add('message', 'textarea')
                ->getForm();
        $request = $this->getRequest();
        if ($request->getMethod() == 'POST') {
            $form->bindRequest($request);
            if ($form->isValid()) {
                $data = $form->getData();
                $container = $this->container;

                $subject = 'Educino - Contact Email';
                $message = $this->renderView('KatebaSiteBundle:Site:contact-us-email.html.twig', array('data' => $data));
                $headers = 'From: Educino <' . $container->getParameter('admin_notifications_email') . '>' . "\r\n";
                $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
                mail($container->getParameter('admin_notifications_email'), $subject, $message, $headers);
//                $message = \Swift_Message::newInstance()
//                        ->setSubject('Educino - Contact Email')
//                        ->setFrom($data['email'])
//                        ->setTo($container->getParameter('admin_notifications_email'))
//                        ->setBody($this->renderView('KatebaSiteBundle:Site:contact-us-email.html.twig', array('data' => $data)), 'text/html')
//                ;
//                $container->get('mailer')->send($message);
                $request->getSession()->getFlashBag()->set('contactEmailSent', true);
                return $this->redirect($this->generateUrl('contact_us'));
            }
        }
        return $this->render('KatebaSiteBundle:Site:contactUs.html.twig', array(
                    'form' => $form->createView()
        ));
    }

    /**
     * @author Mahmoud
     * @param string $_locale
     */
    public function aboutAction($_locale) {
        if ($_locale === 'ar') {
            $aboutPath = __DIR__ . '/../../../../web/site-pages/about-ar.html';
        } else {
            $aboutPath = __DIR__ . '/../../../../web/site-pages/about-en.html';
        }
        $content = file_get_contents($aboutPath);
        return $this->render('KatebaSiteBundle:Site:about.html.twig', array('content' => $content));
    }

    /**
     * @author Mahmoud
     * @param string $_locale
     */
    public function testimonialsAction($_locale) {
        $em = $this->getDoctrine()->getEntityManager();
        $testimonialRepo = $em->getRepository('KatebaSiteBundle:Testimonial');

        $testimonials = $testimonialRepo->findBy(array(), array('priority' => 'desc'));
        return $this->render('KatebaSiteBundle:Site:testimonials.html.twig', array(
                    'testimonials' => $testimonials
        ));
    }

    /**
     * @author Mahmoud
     * @param string $_locale
     */
    public function scholarshipsAction($_locale) {
        if ($_locale === 'ar') {
            $aboutPath = __DIR__ . '/../../../../web/site-pages/scholarships-ar.html';
        } else {
            $aboutPath = __DIR__ . '/../../../../web/site-pages/scholarships-en.html';
        }
        $content = file_get_contents($aboutPath);
        return $this->render('KatebaSiteBundle:Site:scholarships.html.twig', array('content' => $content));
    }

}
